package com.zs.protocol;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Date;

import com.zs.helper.DownLoadHelper;

public class DownLoadProImpl implements DownLoadProcess {
	private ByteBuffer buffer;
	public DownLoadProImpl() {
		buffer=ByteBuffer.allocate(1024);
	}
	
	public void isAcceptable(SelectionKey key) throws IOException {
		ServerSocketChannel serverChannel=(ServerSocketChannel) key.channel();
		SocketChannel mChannel=serverChannel.accept();
		mChannel.configureBlocking(false);
		mChannel.register(key.selector(), SelectionKey.OP_READ);//注册读选择器
		
	}

	
	public void isReadable(SelectionKey key) throws IOException {
		buffer.clear();
		SocketChannel mChannel=(SocketChannel) key.channel();
		InetSocketAddress addr=(InetSocketAddress) mChannel.getRemoteAddress();
		int port=addr.getPort();
		String host=addr.getHostString();
		mChannel.read(buffer);
		buffer.flip();
		
		byte[] value=buffer.array();
		String str=new String(value,0,value.length);
		System.out.println("[HOST:"+host+",PORT:"+port+"]-->"+str);
		DownLoadHelper helper=new DownLoadHelper();
		helper.setFlag(str);
		mChannel.register(key.selector(), SelectionKey.OP_WRITE,helper);//注册写选择器
		
		
	}

	
	public void isWritable(SelectionKey key) throws IOException {
		DownLoadHelper helper=(DownLoadHelper) key.attachment();
		SocketChannel mChannel=(SocketChannel) key.channel();
		int len=helper.read();
		if(len<=0){
			System.out.println("["+new Date().toLocaleString()+"]"+helper.getFlag()+"-->客户端下载结束");
			//关闭频道
			if(mChannel!=null){
				mChannel.close();	
			}
			helper.close();
			
		}else{
			mChannel.write(helper.getBuffer());
		}
		
	}

	
	public void handler(SelectionKey key) throws Exception {
		if(key.isAcceptable()){
			isAcceptable(key);
		}else if(key.isReadable()){
			isReadable(key);
		}else if(key.isWritable()){
			isWritable(key);
		}
		
	}


}
